<template>
  <div class="app-container">

  <el-button-group style="margin-left: 1%;float: left;margin-left: 0.6%;margin-top: 0.2%;margin-bottom: 0.6%;">
        <el-button :disabled="userState" size="medium"  type="primary" @click="addBtn" round>添加</el-button>
      </el-button-group>


    <div class="filter-container" style="margin-left:100px;">
      <el-input
      :disabled="userState"
        v-model="queryForm.cardNo"
        placeholder="卡号"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />
         <el-input
         :disabled="userState"
        v-model="queryForm.phone"
        placeholder="电话"
        style="width: 200px;margin-left: 10px;"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />
      <el-button
      :disabled="userState"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 5px"
        @click="queryBtn"
      >
        查询
      </el-button>
  </div>



    <el-table
      :header-cell-style="{ background: '#ffffff', color: '#000000' }"
      :key="tableKey"
      :row-class-name="tableRowClassName"
      v-loading="listLoading"
      :data="list"
      :row-key="'cardNo'"
      :stripe=true
      ref="ebCardTable"
      @selection-change="handleTableChange"
      border
      fit
      highlight-current-row
      style="
        width: 100%;
        font-size: 15px;
        box-shadow: 1px 1px 8px #cdcdcd;
        border: 0px;
      "
      :default-sort="{ prop: 'time', order: 'descending' }"
    >
      <el-table-column label="卡号" min-width="200px">
        <template slot-scope="scope">
          <span>{{ scope.row.cardNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" min-width="220px">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

       <el-table-column label="手机号" min-width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column label="身份证号" min-width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.idCard }}</span>
        </template>
      </el-table-column>

      <el-table-column label="余额" min-width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.balance }}</span>
        </template>
      </el-table-column>

       <el-table-column prop="parkfieldIds" label="设置场站" width="120"  align="center">
           <template slot-scope="scope">
              <el-tag v-if="scope.row.parkfieldIds == null" size="medium" type="danger">未设置</el-tag>
              <el-tag v-else-if="scope.row.parkfieldIds != null" size="medium" type="success">已设置</el-tag>
           </template> 
      </el-table-column>

      <el-table-column prop="status" label="状态" width="120" fixed="right" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == '0'" size="medium" type="info" effect="dark">未使用</el-tag>
              <el-tag v-else-if="scope.row.status == '1'" size="medium" type="success" effect="dark">使用中</el-tag>
              <el-tag v-else-if="scope.row.status == '2'" size="medium" type="warning" effect="dark">挂失中</el-tag>
              <el-tag v-else-if="scope.row.status == '3'" size="medium" type="danger" effect="dark">已注销</el-tag>
            </template>
          </el-table-column>
      <el-table-column label="操作" width="300" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button :disabled="userState" v-if="scope.row.status == '1'"  size="mini" type="success" @click="goRecharger(scope.$index, scope.row)" title="充值">充值</el-button>
              <el-button :disabled="userState" v-if="scope.row.status == '1'"  size="mini" type="warning" @click="reportLossEBCard(scope.$index, scope.row)" title="挂失">挂失</el-button>
              <el-button :disabled="userState" v-if="scope.row.status == '2'"  size="mini" type="warning" @click="reportLossEBCardNo(scope.$index, scope.row)" title="挂失">取消挂失</el-button>
              <el-button :disabled="userState" v-if="scope.row.status != '3'"  size="mini" type="danger" @click="cancelEBCard(scope.$index, scope.row)" title="注销">注销</el-button>             
            </template>
      </el-table-column>

    </el-table>

    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination
          layout="total,sizes,prev, pager,next,jumper"
           style="margin-top: 10px;"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="handlePageChange"
          @current-change="handleNoChange"
        ></el-pagination>
      </el-col>
    </el-row>


<el-dialog title="充值" :visible.sync="rechargerDialog" :width="'422px'" :destroy-on-close="true">
      <el-form :model="form" :rules="ebCardRules" ref="form">
        <el-form-item label="卡号" :label-width="labelWidth" prop="cardNo">
          <el-input v-model="form.cardNo" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="labelWidth" prop="phone">
          <el-input v-model="form.phone" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="余额" :label-width="labelWidth" prop="balance">
          <el-input v-model="form.balance" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="充值金额" :label-width="labelWidth" prop="amount">
          <el-input v-model="form.amount" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargerDialog = false">取 消</el-button>
        <el-button type="primary" @click="recharger">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加" :visible.sync="addDialog" :width="'422px'" :destroy-on-close="true">
      <el-form :model="addForm" :rules="addRules" ref="addForm">
        <el-form-item label="姓名" :label-width="labelWidth2" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="卡号" :label-width="labelWidth2" prop="cardNo">
          <el-input v-model="addForm.cardNo" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="labelWidth2" prop="phone">
          <el-input v-model="addForm.phone" auto-complete="off"></el-input>
        </el-form-item>
  

<el-form-item label="场地名称" :label-width="labelWidth2" prop="">
  <el-select
    v-model="ruleForm.parkfieldIds"
    style="width: 100%"
    multiple
    filterable
    allow-create
    default-first-option
    placeholder="请选择场地">
    <el-option key="0" label="全部" :value="0"></el-option>
    <el-option
      v-for="item in props"
      :key="item.value"
      :label="item.label"
      :value="item.value"
     />
  </el-select>
</el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<style>

.page-tool {
  background: rgb(237, 231, 231);
}

.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}
.operateBtn {
  font-size: 18px;
  width: 32px;
  height: 32px;
  padding: 0;
}

.el-table .warning-row {
  background: #fff5ee;
}
.el-table__body tr:hover > td {
  background-color: #fdc091;
}
.el-table__body tr.current-row > td {
  background-color: #fdc091;
}
</style>


<script>

import waves from "@/directive/waves"; // waves directive
import { loadEBCardApi, rechargerApi, cancelEBCardApi, reportLossEBCardApi, addApi, delApi, batchDelApi,} from "@/api/bike";



import { loadParkfieldApi } from "@/api/bike";

import { getNickName, getTestUserName } from "../../utils/auth";



import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination



export default {



name: "ebCard",
  data: function () {
    return {
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      loading: false,


      list: [],
      pageNo: 1,
      pageSize: 20,
      total: 0,
      listLoading: true,

      labelWidth2:"100px",
      multipleSelection: [],
      rechargerDialog: false,
      labelWidth: "100px",
      selected: "",
      tableKey: 0,
      addDialog: false,
      labelWidth: "120px",
      form: {},
      hours: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
      roleIndex: true,
      loading: false,
      labelWidth: "150px",
      currentPage: 1,
      ruleForm: {
        roleId: '',
        parkfieldIds: [],
        cardNo: '',
      },
      props: [],
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name: undefined,
        phone: undefined,
        number: undefined,
        sort: "+id",
      },

      ebCard: [],
      form: {
        cardNo: '',
        phone: '',
        amount: '',
        balance: '',
      },
      queryForm: {
        cardNo: '',
        phone: '',
      },

      parkfieldList: "",
      value: [],
      
      roleIndex: true,
      addForm: {
        parkfieldIds:null,
        name: null,
        cardNo: null,
        phone: null,
        idCard: null,
      },

      addDialog: false,

      ebCardRules: {
        amount: [
            { required: true, message: '请输入充值金额', trigger: 'blur' },
            { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确的充值金额' },
          ],
      },

      addRules: {
        name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
        cardNo: [
            { required: true, message: '请输入卡号', trigger: 'blur' },
          ],
        phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
          ],
        idCard: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
          ],
      },

    };
  },

  created() {},

  mounted: function () {
     this.$nextTick(function () {
      let _this = this;
      _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
    });
  },

  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  

  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 0) {
        return "warning-row";
      }
      return "";
    },

 
    handleFilter() {
      this.listQuery.pageNo = 1;
   //   this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success",
      });
      row.status = status;
    },


 //列表页码的触发事件
    handlePageChange(pageSize) {
      this.pageSize = pageSize;
      this.loadEBCard(this.pageNo, this.pageSize);
    },
    handleNoChange(pageNo) {
      this.pageNo = pageNo;
      this.loadEBCard(this.pageNo, this.pageSize);
    },
    handleTableChange(val) {
      this.multipleSelection = val;
    },
    loadEBCard(pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadEBCardApi({
        pageNo: pageNo,
        pageSize: pageSize,
        cardNo:_this.queryForm.cardNo,
        phone:_this.queryForm.phone,
        roleCode:this.$store.state.mainpart.key

      }).then((response) => {
        _this.list = response.data.dataList;
        _this.total = response.data.totalNum;
        setTimeout(() => {
          _this.listLoading = false;
        }, 1 * 1000);
      });
    },



    handleCellDbclick (row, column, cell, event) {
      console.log(column.property);
      if (column.property === "userName") {
        this.userForm = {
          id: row.lockId,
          userId: row.userId
        };
      } else {
        
      }
    },

    queryBtn () {
      let _this = this
      _this.loading = true
      // console.log("_this.queryForm: {}", _this.queryForm);
      _this.loadEBCard (_this.pageNo, _this.pageSize, _this.queryForm)
      // console.log("_this.ebCard: {}", _this.ebCard);
    },

    addBtn () {
      let _this = this;
      _this.addForm = {
        parkfieldIds:null,
        name: null,
        cardNo: null,
        phone: null,
        idCard: null,
        
      };
      _this.ruleForm = {
        parkfieldIds:[],
        roleId:null
      }
      
      _this.addDialog = true;
      _this.loadParkfield();
      

    },

    loadParkfield () {

    loadParkfieldApi().then(res => {
    this.props = res.data.map((item) => {
          return { value: item.id, label: item.name }
        });

    // this.props.add('全部',0);
})

    },

    add (){
      let _this = this;
      _this.$refs.addForm.validate((valid) => {
        if (valid) {
          if(_this.ruleForm.parkfieldIds.includes(0)){
            _this.ruleForm.parkfieldIds = '0'
          }
          _this.ruleForm.parkfieldIds = _this.ruleForm.parkfieldIds.join();
          
          _this.addForm.parkfieldIds = _this.ruleForm.parkfieldIds
          addApi(_this.addForm).then(resp => {
            _this.addDialog = false;
            _this.ruleForm.cardNo=_this.addForm.cardNo;
            if (resp.errmsg === 'ok') {
                _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
                // addApi(_this.ruleForm).then(res => {
                
                
                // })
                _this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success'
                })
              } else {
                _this.$notify({
                  title: '失败',
                  message: '添加失败',
                  type: 'error'
                })
              }
          });
        }
      })
    },

    del (index, row) {
      let _this = this
      this.$confirm('确认删除', '提示', {
        type: 'warning'
      })
        .then(_ => {
          delApi(row).then(function (resp) {
            if (resp.errmsg === 'ok') {
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success'
              })
            }else {
                _this.$notify({
                  title: '失败',
                  message: '删除失败',
                  type: 'error'
                })
              }
          })
        })
    },

    batchDelete () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择",
          type: "warning"
        });
        return;
      }
      let _this = this;
      this.$confirm('确认批量删除', '提示', {
        type: 'warning'
      })
        .then(_ => {
          batchDelApi(this.multipleSelection).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.ebCardTable.clearSelection();
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "删除失败",
                type: "error"
              });
            }
          });
        })

    },

    recharger () {
      let _this = this;
      _this.$refs.form.validate((valid) => {
        if (valid) {
          rechargerApi(_this.form.cardNo, _this.form.amount).then(resp => {
            console.log(resp)
            if (resp.data === "OK") {
              _this.rechargerDialog = false;
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: "成功",
                message: "充值成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "充值失败",
                type: "error"
              });
            }
          });
        }
      });
    },

    goRecharger(index, row) {
      let _this = this;
      _this.form = {
        cardNo: row.cardNo,
        phone: row.phone,
        amount: '',
        balance: row.balance,
      };
      console.log(_this.form)
      _this.rechargerDialog = true;
      // _this.$nextTick(()=>{
      //   if(_this.$refs.form != undefined){
      //     _this.$refs.form.resetFields();
      //   }
      // })
    },

    cancelEBCard (index, row) {
      let _this = this;
      this.$confirm('确认注销', '提示', {
        type: 'warning'
      })
        .then(_ => {
          row.status = 3
          cancelEBCardApi(row).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.ebCardTable.clearSelection();
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: "成功",
                message: "注销成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "注销失败",
                type: "error"
              });
            }
          });
        })
    },

    reportLossEBCard (index, row) {
      let _this = this;
      this.$confirm('确认挂失', '提示', {
        type: 'warning'
      })
        .then(_ => {
          row.status = 2
          reportLossEBCardApi(row).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.ebCardTable.clearSelection();
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: "成功",
                message: "挂失成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "挂失失败",
                type: "error"
              });
            }
          });
        })
    },

    reportLossEBCardNo (index, row) {
      let _this = this;
      this.$confirm('确认取消挂失', '提示', {
        type: 'warning'
      })
        .then(_ => {
          row.status = 1
          reportLossEBCardApi(row).then(function (resp) {
            if (resp.errmsg === "ok") {
              _this.multipleSelection = []
              _this.$refs.ebCardTable.clearSelection();
              _this.loadEBCard(_this.pageNo, _this.pageSize, _this.queryForm);
              _this.$notify({
                title: "成功",
                message: "取消挂失成功",
                type: "success"
              });
            }else {
              _this.$notify({
                title: "失败",
                message: "取消挂失失败",
                type: "error"
              });
            }
          });
        })
    }
  }
}

</script>